<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 流年 <liu21st@gmail.com>
// +----------------------------------------------------------------------

// 应用公共文件
/**
 * [p 数组]
* @return [type] [description]
*/
function p($arr){
	echo "<pre>".print_r($arr,true)."</pre>";
}
/**
 * 由当前时间戳 + 5位随机数生成文件名
 * @return int 生成文件名
 */
function create_filename() {
	return time () . mt_rand ( 10000, 99999 );
}

/**
 * [check_mobile 校验 手机格式]
 * @param  [type] $phone [description]
 * @return [type]        [description]
 */
function check_mobile($phone){
	return preg_match("/1\d{10}$/",$phone);
}

/**
 * [check_email 校验邮箱格式]
 * @param  [type] $email [description]
 * @return [type]        [description]
 */
function check_email($email){
	$pattern = "/^([0-9A-Za-z\\-_\\.]+)@([0-9a-z]+\\.[a-z]{2,3}(\\.[a-z]{2})?)$/i";
	return preg_match($pattern,$email);
}


/**
 * 用户密码加密方法，可以考虑盐值包含时间（例如注册时间），
 * @param string $pass 原始密码
 * @return string 多重加密后的32位小写MD5码
 */
function encrypt_pass($pass) {
	if ('' == $pass) {
		return '';
	}

	$salt = config ( 'system.pass_salt');
	return md5 ( sha1 ( $pass ) . $salt );
}

/**
 * CURL快捷方法，post提交数据
 * @param string $url 提交目的地址
 * @param array $data post数据
 * @return url访问结果
 */
function curl_post($url, $data) {
	$ch = curl_init ();
	$header = array ("Accept-Charset: utf-8",'Expect:' );
	curl_setopt ( $ch, CURLOPT_URL, $url );
	curl_setopt ( $ch, CURLOPT_CUSTOMREQUEST, "POST" );
	curl_setopt ( $ch, CURLOPT_SSL_VERIFYPEER, FALSE );
	curl_setopt ( $ch, CURLOPT_SSL_VERIFYHOST, FALSE );
	curl_setopt ( $ch, CURLOPT_HTTPHEADER, $header );
	curl_setopt ( $ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)' );
	curl_setopt ( $ch, CURLOPT_FOLLOWLOCATION, 1 );
	curl_setopt ( $ch, CURLOPT_AUTOREFERER, 1 );
	curl_setopt ( $ch, CURLOPT_TIMEOUT, 60 );
	// 最好加上http_build_query 转换，防止有些服务器不兼容
	curl_setopt ( $ch, CURLOPT_POSTFIELDS, http_build_query ( $data ) );
	curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, true );
	$result = curl_exec ( $ch );
	curl_close ( $ch );
	return $result;
}

/**
 * CURL快捷方法，get提交数据
 * @param string $url 提交目的地址
 * @param array $data post数据
 * @return url访问结果
 */
function curl_get($url, $data) {
	$ch = curl_init ();
	$header = array ("Accept-Charset: utf-8",'Expect:' );
	$url = $url .'?'.http_build_query($data);
	curl_setopt ( $ch, CURLOPT_URL, $url );
	curl_setopt ( $ch, CURLOPT_CUSTOMREQUEST, "GET" );
	curl_setopt ( $ch, CURLOPT_SSL_VERIFYPEER, FALSE );
	curl_setopt ( $ch, CURLOPT_SSL_VERIFYHOST, FALSE );
	curl_setopt ( $ch, CURLOPT_HTTPHEADER, $header );
	curl_setopt ( $ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)' );
	curl_setopt ( $ch, CURLOPT_FOLLOWLOCATION, 1 );
	curl_setopt ( $ch, CURLOPT_AUTOREFERER, 1 );
	curl_setopt ( $ch, CURLOPT_TIMEOUT, 60 );

	curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, true );
	$result = curl_exec ( $ch );
	curl_close ( $ch );
	return $result;
}

/**
 * 获取手机验证码
 * @param string $phone
 * @param string $pre :register , login, findpwd
 * @return string
 */
function get_sms_verify_code($phone,$pre = '') {
	//数据库保存
	$phone = $pre.'_'.$phone;
	$result = db('phone_code')->where('phone',$phone)->field('code,deadline')->find();
	if (empty( $result )){
		$data['code'] = createRandomCode();
		$data['phone'] = $phone;
		$data['deadline'] = time() + 10*60;
			
		db('phone_code')->insert($data);
		return $data['code'];
			
	}else if( $result['deadline'] < time() ){
		$data['code'] = createRandomCode();
		$data['deadline'] = time() + 10*60;
		db('phone_code')->where('phone',$phone)->update($data);
		return $data['code'];
	}

	return $result['code'];
}

/**
 * 手机验证码检测
 * @param string $phone
 * @param string $inputCode
 * @param string $pre :register , login, findpwd
 * @return boolean
 */
function check_sms_verify_code($phone, $inputCode,$pre = '') {
	//TODO 数据库比对
	$phone = $pre.'_'.$phone;
	$result = db('phone_code')->where('phone',$phone)->field('code,deadline')->find();
	if( empty($result) || $result['deadline'] < time() ){
			
		return msg_return( 0  , '验证码已失效，请重新获取！' );
	}else if( $result['code'] != $inputCode ){
		return msg_return( 0  , '验证码不正确！' );
	}

	return msg_return( 1  , 'ok' );

}



/**
 * 生成随机验证码，每一位都是单独从字典中随机获取的字符，字典是0-9纯数字。
 * @param number $length 验证码长度，默认6
 * @return string 指定长度的随机验证码。
 */
function createRandomCode($length = 6) {
	$chars = "0123456789";
	$str = "";
	for($i = 0; $i < $length; $i ++) {
		$str .= substr ( $chars, mt_rand ( 0, strlen ( $chars ) - 1 ), 1 );
	}

	return $str;

}

/**
 * 发送短信，当前代码以吉信通为短信平台，使用其他平台时需要重写方法
 * @param string $phone 短信目的手机号，格式由短信平台决定，一般为单手机号或者逗号分割的多手机号
 * @param string $content 短信内容
 * @return boolean 是否发送成功
 */
function sendSms_bak($phone, $content) {
	// 数据库读取短信平台账号密码
	$smsConfig = Db( 'config' )->where ( 'confName' , 'sms' )
	->value ('confValue');
	$smsConfig = json_decode($smsConfig,true);
	$userName = $smsConfig ['userName'];
	$pass = $smsConfig ['pass'];
	// 从配置读取短信平台服务器
	$sendUrl = $smsConfig ['url'];

	// 短信要转换成gbk的 不然短信是乱码
	$oriContent = $content;
	$content = iconv ( "UTF-8", "gb2312", $content );

	return true;//测试TODO

	// 调用短信平台接口发送
	$data = array ("id" => $userName,"pwd" => $pass,"to" => $phone,"content" => $content,
			"time" => '' );
	$sendResult = curl_post ( $sendUrl, $data );

	// 接口返回结果解析，日志记录
	$smsInfo = '[目的手机]：' . $phone . '[短信内容]：' . $oriContent . '。';
	$tempArray = explode ( '/', $sendResult, 2 );
	if ($tempArray [0] == '000') {
		\Think\Log::record ( '[短信发送成功]。' . $smsInfo, \Think\Log::INFO );
		return true;
	} else {
		\Think\Log::record ( '[短信发送失败]' . $sendResult . '。' . $smsInfo, \Think\Log::NOTICE );
		return false;
	}
}


/**
 * 检测用户是否登录
 * @return integer 0-未登录，大于0-当前登录用户ID
 */
function is_login(){
	$admin = session('admin_auth');
	if (empty($admin)) {
		return 0;
	} else {
		return session('admin_auth_sign') == data_auth_sign($admin) ? $admin['uid'] : 0;
	}
}


/**
 * 数据签名认证
 * @param  array  $data 被认证的数据
 * @return string       签名
 */
function data_auth_sign($data) {
	//数据类型检测
	if(!is_array($data)){
		$data = (array)$data;
	}
	ksort($data); //排序
	$code = http_build_query($data); //url编码并生成query字符串
	$sign = sha1($code); //生成签名
	return $sign;
}



/**
 * 返回json
 * @param array $data
 */
function json_return( $data = array() ){
	// 返回JSON数据格式到客户端 包含状态信息
	header('Content-Type:application/json; charset=utf-8');
	exit(json_encode($data));
}

/**
 * 格式化参数格式化成url参数
 */
function to_url_params($data)
{
	$buff = "";
	foreach ($data as $k => $v)
	{
		if( $v != "" && !is_array($v)){
			$buff .= $k . "=" . $v . "&";
		}
	}

	$buff = trim($buff, "&");
	return $buff;
}

/**
 * 抛出异常处理
 * @param string    $msg  异常消息
 * @param integer   $code 异常代码 默认为0
 * @param string    $exception 异常类
 *
 * @throws Exception
 */
function my_exception($msg = null, $code = 0, $exception = '')
{
	if ($msg == null){
		$msgDefault = config ( 'error' );
		$msg = $msgDefault [$code];
	}else{
		$msg = $msg ;
	}



	$e = $exception ?: '\think\Exception';
	throw new $e($msg, $code);
}

/**
 * 返回格式化信息
 * @param string/array $msg 信息内容
 * @param string $code 错误码
 * @param number $status 状态 0 错误 ，1 成功
 * @return array
 */
function msg_return($status = 0  ,$msg = null , $code = 0) {

	return array ('status' => $status, "code" => $code ,"msg" => $msg );
}


/**
 * ajax 请求正确返回
 * @param string $msg
 * @param array $data
 * @return json
 */
function ajax_return_ok($data = array(),$msg = ''){

	$result['status'] = 1;
	$result['data'] = $data;
	$result['msg'] = $msg ;
	// 返回JSON数据格式到客户端 包含状态信息
	header('Content-Type:application/json; charset=utf-8');
	exit(json_encode($result));
}

/**
 * ajax 请求错误返回
 * @param string $msg
 * @param string $code
 * @return json
 */
function ajax_return_error($msg = null,$code = 1){

	if ($msg == null){
		$msgDefault = config ( 'error' );
		$result['msg'] = $msgDefault [$code];
	}else{
		$result['msg'] = $msg ;
	}

	$result['status'] = 0;
	$result['code'] = $code;
	// 返回JSON数据格式到客户端 包含状态信息
	header('Content-Type:application/json; charset=utf-8');
	exit(json_encode($result));
}

